from codeflow.browser.models import sync_changesets
from codeflow import settings
from django.core.exceptions import ImproperlyConfigured
import time
import threading


class SyncThread(threading.Thread):
    """
    Simple thread that first calls codeflow.browser.models.sync_changesets and then
    invokes the callback specified on the constructor
    """
    def __init__(self, callback):
        self.callback = callback
    def run(self):
        sync_changesets()        
        self.callback()

class SCMSyncMiddleware(object):
    """
    Synchronizes changesets if more than CODEFLOW_SCM_SYNC_SECONDS have elapsed
    since last synchronization
    """
    def __init__(self):
        self.last_sync = 0
        self.synching_lock = threading.Lock()
        if not hasattr(settings, 'CODEFLOW_SCM_SYNC_SECONDS'):
            raise ImproperlyConfigured, \
                  "CODEFLOW_SCM_SYNC_SECONDS settings not specified"
    def process_request(self, request):
        not_currently_synching = self.synching_lock.acquire(False)
        if not_currently_synching:
            now = time.time()
            if now - self.last_sync > settings.CODEFLOW_SCM_SYNC_SECONDS:
                print "SCMSyncMiddleware: Sync started"
                self.last_sync = now
                t = SyncThread(self._sync_done)
                t.run()
            else:
                self.synching_lock.release()
    def _sync_done(self):
        self.synching_lock.release()
        print "SCMSyncMiddleware: Sync finished"

